/*
 * Copyright 2018-2019 KunMinX
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wanchuang.hepos.ui.page.login;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.data.bean.UserBean;
import com.wanchuang.hepos.bridge.request.LoginRequestViewModel;
import com.wanchuang.hepos.bridge.state.login.MENetworkOneViewModel;
import com.wanchuang.hepos.databinding.FragmentMeNetworkOneBinding;
import com.wanchuang.hepos.help.ImageHelper;
import com.wanchuang.hepos.help.PermissionHelper;
import com.wanchuang.hepos.help.UserHelper;
import com.wanchuang.hepos.ui.base.BaseFragment;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.List;

import static android.app.Activity.RESULT_OK;


/**
 * Create by KunMinX at 19/10/29
 */
public class MENetworkOneFragment extends BaseFragment {

    private FragmentMeNetworkOneBinding mBinding;
    private MENetworkOneViewModel mViewModel;
    private LoginRequestViewModel mLoginRequestViewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MENetworkOneViewModel.class);
        mLoginRequestViewModel = ViewModelProviders.of(this).get(LoginRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_me_network_one, container, false);
        mBinding = FragmentMeNetworkOneBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLoginRequestViewModel.getErrorString().observe(this, error -> {
            hideProgress();
            showShortToast(error);
        });

        // 第一步认证成功调用
        mLoginRequestViewModel.getResultString().observe(this, result -> {
            hideProgress();
            UserBean user = UserHelper.getUser();
            user.setMember_name(mViewModel.name.get());  // 设置真实姓名，绑定银行卡需要用到
            UserHelper.login(user);
            nav().navigate(R.id.action_MENetworkOneFragment_to_MENetworkTwoFragment);
        });


        mLoginRequestViewModel.getCompathone().observe(this, s -> {  // 上传第一步返回
            mViewModel.UploadPath = s;
            mLoginRequestViewModel.upLoadImage(mViewModel.compressPathTwo.get(), mLoginRequestViewModel.getCompathTwo());
        });
        mLoginRequestViewModel.getCompathTwo().observe(this, s -> {  // 上传第二步返回
            mViewModel.UploadPathTwo = s;
            mLoginRequestViewModel.upLoadImage(mViewModel.compressPathThree.get(), mLoginRequestViewModel.getCompathThree());
        });
        mLoginRequestViewModel.getCompathThree().observe(this, s -> {  // 上传第三步返回
            mViewModel.UploadPathThree = s;
            mLoginRequestViewModel.intent(mViewModel.UploadPath, mViewModel.UploadPathTwo,  // 调用认证方法
                    mViewModel.UploadPathThree, mViewModel.name.get(), mViewModel.qrcode.get());
        });


        mSharedViewModel.qrCardString.observe(this, s -> {
            if (mViewModel.selectImageType == 0) {
                mViewModel.compressPath.set(s);
            } else if (mViewModel.selectImageType == 1) {
                mViewModel.compressPathTwo.set(s);
            }
        });
    }


    public class ClickProxy {
        public void submit() {
            String name = mViewModel.name.get();
            if (TextUtils.isEmpty(name)) {
                showShortToast("请输入姓名");
                return;
            }
            String qrcode = mViewModel.qrcode.get();
            if (TextUtils.isEmpty(qrcode)) {
                showShortToast("请输入身份证号码");
                return;
            }
            if (qrcode.length() < 18) {
                showShortToast("请输入18位身份证号码");
                return;
            }
            // 开始上传
            getSharedViewModel().isLoading.setValue(true);
            mLoginRequestViewModel.upLoadImage(mViewModel.compressPath.get(), mLoginRequestViewModel.getCompathone());
        }

        public void back() {
            mSharedViewModel.isShowLoginOut.setValue(true);
        }

        public void selectPicture(int type) {
            PermissionHelper.getInstance().getPermission(mActivity, new PermissionHelper.PermissionCallBack() {
                @Override
                public void onSuccess() {
                    mViewModel.selectImageType = type;
                    ImageHelper.showSelectChoose(MENetworkOneFragment.this);
                }

                @Override
                public void onFail() {
                    showShortToast("请先允许权限再使用此功能");
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }


        public void selectQrCard(int type) {
            PermissionHelper.getInstance().getPermission(mActivity, new PermissionHelper.PermissionCallBack() {
                @Override
                public void onSuccess() {
                    mViewModel.selectImageType = type;
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 1);
                    nav().navigate(R.id.action_changeJieSuanKaFragment_to_takeCardPhotoFragment, bundle);
                }

                @Override
                public void onFail() {
                    showShortToast("请先允许权限再使用此功能");
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            if (mViewModel.selectImageType == 2) {
                mViewModel.compressPathThree.set(localMedias.get(0).getPath());
            }
        }
    }
}
